import PermissionControl from '@/components/PermissionControl/index';
import { deleteFollowUp, getFollowUpList } from "@/services/patient/followUpApi";
import { showMsg } from "@/utils/utils";
import { ProFormDateRangePicker } from "@ant-design/pro-form";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import { Popconfirm } from "antd";
import { useRef, useState } from "react";
import QuestionnaireForm, { ResultInfo } from "./questionnaireForm";

const ManageTab = () => {

  const actionRef = useRef<ActionType>();
  const [open, setOpen] = useState<boolean>(false);
  const [resultInfo, setResultInfo] = useState<ResultInfo>();
  const [readonly, setReadonly] = useState<boolean>(false);

  const columns: ProColumns<PATIENT.FollowUpInfo>[] = [
    {
      title: '随访订单',
      dataIndex: 'order_id',
      colSize: 3
    },
    {
      title: '患者编号',
      dataIndex: 'patient_id',
      colSize: 3
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      colSize: 3
    },
    {
      title: '身份证/住院号',
      dataIndex: 'identity_no',
      formItemProps: { labelCol: { flex: '0 0 90px' } },
      colSize: 3
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      colSize: 3
    },
    {
      title: '随访时间',
      dataIndex: 'timestamp',
      colSize: 3,
      renderFormItem: ({ dataIndex }) => (
        <ProFormDateRangePicker
          name={dataIndex}
          placeholder={undefined}
          fieldProps={{ allowEmpty: [true, true] }}
          wrapperCol={{ flex: '0 0 calc(100% + 6px)', style: { maxWidth: 'unset' } }}
        />
      )
    },
    {
      title: '执行人',
      dataIndex: 'executor_name',
      search: false
    },
    {
      title: '状态',
      dataIndex: 'partake_status',
      valueEnum: {
        W: '待参与',
        P: '已参与',
        L: '忽略'
      },
      colSize: 3
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record, idx, action) => (
        <div style={{ display: 'inline-flex', gap: 24 }}>
          {
            record.partake_status === 'P'
              ? <PermissionControl action_id="900901003">
                <a onClick={() => {
                  setResultInfo({
                    survey_id: record.survey_test_id as string,
                    patient_id: record.patient_id as string,
                    order_id: record.order_id as string
                  });
                  setReadonly(true);
                  setOpen(true);
                }}>详情</a>
              </PermissionControl>
              : <>
                <PermissionControl action_id="900901001">
                  <a onClick={() => {
                    setResultInfo({
                      survey_id: record.survey_test_id as string,
                      patient_id: record.patient_id as string,
                      order_id: record.order_id as string
                    });
                    setReadonly(false);
                    setOpen(true);
                  }}>填写随访</a>
                </PermissionControl>
                <PermissionControl action_id="900901002">
                  <Popconfirm placement="topRight" title='确认删除？' onConfirm={async () => {
                    if (!record.survey_test_id) return;
                    try {
                      await deleteFollowUp(record.patient_id, record.order_id, record.survey_test_id);
                      showMsg('删除成功', 'success');
                      action?.reload();
                    } catch (error: any) {
                      showMsg(error?.data?.errmsg);
                    }
                  }}>
                    <a>删除</a>
                  </Popconfirm>
                </PermissionControl>
              </>
          }
        </div >
      )
    }
  ];

  return <>
    <ProTable<PATIENT.FollowUpInfo>
      actionRef={actionRef}
      rowKey="timestamp"
      className='mytable'
      options={false}
      bordered
      search={{
        span: 2,
        labelWidth: 64,
        collapsed: false,
        collapseRender: false,
        style: { padding: '0 6px 0 20px' },
        optionRender: (_, __, [, queryBtn]) => [queryBtn]
      }}
      columns={columns}
      request={async (params) => {
        try {
          const res = await getFollowUpList({ ...params });
          return { success: true, data: res.record_list, total: res.sum_record_num };
        } catch (reason) {
          return { success: false, data: [] };
        }
      }}
      toolbar={{ style: { borderTop: '2px solid #eee', marginBottom: -6 } }}
      pagination={{ showQuickJumper: true }}
    />
    <QuestionnaireForm resultInfo={resultInfo} readonly={readonly} apply={true} open={open} openChange={open => {
      if (!open) {
        actionRef.current?.reload();
        setResultInfo(undefined);
        setReadonly(false);
      }
      setOpen(open);
    }} />
  </>;
};

export default ManageTab;
